package cn.myzqu.sign.common.qcloud.cos;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;

import java.io.File;

/**
 * @Author: 的川
 * @Date: 2018/12/24.
 */
public class COSTemplate {

    /**
     *  开发者拥有的项目身份识别 ID，用以身份认证
     */
    private  String secretId ;
    /**
     * 开发者拥有的项目身份密钥
     */
    private  String secretKey ;
    /**
     * COS 中用于存储数据的容器
     */
    private  String bucket ;
    /**
     * 域名中的地域信息
     */
    private  String region ;

    public String getSecretId() {
        return secretId;
    }

    public void setSecretId(String secretId) {
        this.secretId = secretId;
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
    }

    public String getBucket() {
        return bucket;
    }

    public void setBucket(String bucket) {
        this.bucket = bucket;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }


    /**
     * 上传单个文件到腾讯对象存储
     * @param localFile
     * @return
     */
    public  String uploadFile(File localFile) {
        // 1 初始化
        // 1.1 初始化用户身份信息(secretId, secretKey)
        COSCredentials cred = new BasicCOSCredentials(this.getSecretId(), this.getSecretKey());
        // 1.2 设置bucket的区域
        ClientConfig clientConfig = new ClientConfig(new Region(this.getRegion()));
        // 1.3 生成cos客户端
        COSClient cosClient = new COSClient(cred, clientConfig);
        // 2 上传文件
        //2.1 key必须保持唯一，重复会被重新
        String fileName = localFile.getName();
        System.out.println("上传的文件名为："+fileName);
        //获取原文件的后缀
        String suffix = fileName.substring(fileName.lastIndexOf("."));
        //生成文件名称(唯一key，重复会被重写)
        String key = genUniqueKey() + suffix;
        PutObjectRequest putObjectRequest = new PutObjectRequest(this.getBucket(), key, localFile);
        cosClient.putObject(putObjectRequest);
        //3 关闭客户端
        cosClient.shutdown();
        //4 生成地址并返回:
        //https://ygmall-comment-1255574204.cos.ap-guangzhou.myqcloud.com/1.jpg
        StringBuffer url = new StringBuffer();
        url.append("https://").append(this.getBucket()).append(".cos.")
                .append(this.getRegion()).append(".myqcloud.com/")
                .append(key);
        return url.toString();
    }


    /**
     * 生成唯一的主键
     * 格式: 时间+随机数
     * @return
     */
    private synchronized String genUniqueKey() {
        return ""+System.currentTimeMillis()  ;
    }


}
